/*
 * TableMaker.c
 *
 *  Created on: 03/05/2013
 *      Author: pargo
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <float.h>

typedef struct _tab{
	char name[500];
	float* vl;
	long num;
}tab;

char** headers;

tab table[1000];


int main(int arg, char* argvs[]){

	char* filedefname = argvs[1];
	char* fileinname = argvs[2];
	char* fileoutname = argvs[3];

	FILE* def = fopen(filedefname, "r");
	FILE* input = fopen(fileinname, "r");
	FILE* output = fopen(fileoutname, "w");

	//leh a definição dos arquivos
	long n;
	long i,j;
	fscanf(def, "%lu", &n);

	headers = malloc(sizeof(char*)*n);

	for(i = 0; i < n; i++){
		headers[i] = malloc(sizeof(char)*500);
		fscanf(def, "%s", headers[i]);
		fprintf(output,"%s \t", headers[i]);
	}
	fprintf(output," \n");


	for(i = 0; i < 1000; i++){
		table[i].num = 0;
		table[i].vl = malloc(sizeof(float)* (n));
	}

	//leh os dados de entrada
	long v = 0;
	char name[500];
	float vl[n];

	while(!feof(input)){
		fscanf(input, "%s", &name);
		for( i = 0; i < n-1; i++)
			fscanf(input, "\t%f", &(vl[i]));

		if(strcmp(table[v].name, name))
			v++;

		strcpy(table[v].name, name);
		table[v].num++;
		for( i = 0; i < n-1; i++)table[v].vl[i] += vl[i];
	}


	//computa a tabela final
	for( i = 1; i <= v; i++)
		for(j = 0; j < n-1; j++)table[i].vl[j] = table[i].vl[j]/((float)table[i].num);

	//escreve arquivo de saida

	for(i = 1; i <= v; i++){
		fprintf(output, "%s", table[i].name);
		for(j = 0; j < n-1; j++)fprintf(output, "\t %f", table[i].vl[j]);
		fprintf(output, "\n");
	}

	fclose(output);
	fclose(input);
	fclose(def);
}
